from Products.Five import BrowserView
from Products.CMFCore.utils  import getToolByName
from Products.Five.browser.pagetemplatefile import ViewPageTemplateFile
from Products.CMFCore.permissions import ReviewPortalContent
from Products.CMFPlone.utils import base_hasattr
import json

class IndexView():
    """ index page
    """
    myindex = ViewPageTemplateFile("myindex.pt")
    mycheck = ViewPageTemplateFile("mycheck.pt")
    
    def __init__(self,context,request):
        self.context = context
        self.request = request
    def path(self):
        mt = getToolByName(self, 'portal_membership')
        home = mt.getHomeFolder()
        return '/'.join(home.getPhysicalPath())
    def __call__(self):
        mt = getToolByName(self, 'portal_membership')
        if mt.checkPermission(ReviewPortalContent, self.context):
            return self.mycheck()
        else:
            return self.myindex()
    
class CheckList(BrowserView):
    """Check List
    """
    checkpaid = ViewPageTemplateFile('checklist/checkpaid.pt')
    def __init__(self,context,request):
        self.context = context
        self.request = request
    def __call__(self):
        if base_hasattr(self.request,'checkpaid'):
            return self.checkpaid()
        else:
            return 
class IdsJson:
    """ personal books id
    """
    def __init__(self,context,request):
        self.context = context
        self.request = request
    def __call__(self):
        result = {}
        mt = getToolByName(self.context, 'portal_membership')        
        if mt.isAnonymousUser():
            return '{"Status":"Error","Message":"Please login first "}'
        results = None
        isReviewer = False
        if mt.checkPermission(ReviewPortalContent, self.context):
            ###
            path ='/'.join(self.context.getPhysicalPath())+'/Members'
            results = self.context.portal_catalog.searchResults(path=path,Type="EpubBook")
            isReviewer = True
        else:
            home = mt.getHomeFolder()
            if home == None:
                return '{"Status":"Error","Message":"home folder error. please connect site administrator"}'
            
            member = mt.getAuthenticatedMember()
            username = member.getUserName()
            
            path ='/'.join(self.context.getPhysicalPath())
            
            results = self.context.portal_catalog.searchResults(path=path,Type="EpubBook",Creator=username,sort_on='modified',sort_order='descending')
            
        ids = []
        for item in results:
            if isReviewer:
                 review_state = item.review_state
                 if (review_state in ('unpaid','rejected','paid','checkpaid') ):
                     continue
            ids.append(item.UID)
                
        result['Status'] = 'Success'
        result['Result'] = ids
        return json.dumps(result)